import React, {useCallback, useMemo, useState, useEffect} from 'react';
import {
  ScrollView,
  TouchableOpacity,
  View,
  StyleSheet,
  Animated,
} from 'react-native';
import {BasicText} from '../text';
import {TabItem} from './index';
import {ScreenWidth} from '../../config/devices';
import { normalize } from '../../utils/adapter';

export type Props = {
  tabs: TabItem[];
};

const HorizontalTabs = ({tabs}: Props): JSX.Element => {
  const [curIndex, setCurIndex] = useState<number>(0);

  const [moveAnim] = useState(new Animated.Value(0));

  const itemWidth = useMemo(() => {
    return ScreenWidth / tabs.length;
  }, [tabs.length]);

  const handlePress = useCallback((index: number) => {
    setCurIndex(index);
  }, []);

  useEffect(() => {
    const startMove = () => {
      Animated.timing(moveAnim, {
        toValue: curIndex * itemWidth,
        duration: 300,
        useNativeDriver: true,
      }).start();
    };
    startMove();
  }, [curIndex, itemWidth, moveAnim]);

  return (
    <View style={{height: normalize(50)}}>
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.contentContainer}
        horizontal={true}>
        {tabs.map((v, i) => (
          <TouchableOpacity
            key={v.value}
            style={[styles.item, {width: itemWidth}]}
            onPress={() => handlePress(i)}>
            <View>
              <BasicText color="#333">{v.label}</BasicText>
            </View>
          </TouchableOpacity>
        ))}
      </ScrollView>
      <Animated.View
        style={[
          styles.active_line,
          {width: itemWidth},
          {transform: [{translateX: moveAnim}]},
        ]}>
        <View style={{width: '50%', height: normalize(3), backgroundColor: '#FF685A'}} />
      </Animated.View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: normalize(15),
  },
  contentContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  item: {
    alignItems: 'center',
  },
  active_line: {
    alignItems: 'center',
    marginTop: normalize(5),
  },
});

export default HorizontalTabs;
